package model;

import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;

/**
 * Class to model the filesystem. Extends {@link DefaultTreeModel} for display use in a 
 * {@link JTree}.
 * 
 * @author Chris Moghbel (cmoghbel@ucsd.edu)
 */
@SuppressWarnings("serial")
public class FilesystemTreeModel extends DefaultTreeModel {

  private FilesystemObject _root;
  
  /**
   * Create a new model.
   * 
   * @param root the root of the filesystem
   */
  public FilesystemTreeModel (FilesystemObject root) {
    super (new DefaultMutableTreeNode(root));
    _root = root;
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public Object getChild(Object parent, int index) {
    if (parent instanceof FilesystemObject) {
      return ((FilesystemObject)parent).getChild(index);
    }
    return null;
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public int getChildCount(Object parent) {
    if (parent instanceof FilesystemObject) {
      return ((FilesystemObject)parent).get_numChildren();
    }
    return 0;
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public int getIndexOfChild(Object parent, Object child) {
    if (parent instanceof FilesystemObject) {
      return ((FilesystemObject)parent).get_children().indexOf(child);
    }
    return 0;
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public Object getRoot() {
    return _root;
  }

  /**
   * {@inheritDoc}
   * 
   * Node is considered a leaf if it is not a directory. 
   */
  @Override
  public boolean isLeaf(Object node) {
    if (node instanceof FilesystemObject) {
      return !((FilesystemObject)node).isDirectory();
    }
    return true;
  }
  
}
